#!/usr/bin/env python
from django.core.management import setup_environ
import settings
setup_environ(settings)

import urllib2, time, datetime
from django.utils import simplejson

from arcade.models import Feed, Game, ArcadeCategory
from arcade import adapters

def load_feed(feed):
    try:
        f = urllib2.urlopen(feed.feed_location)
        feed_contents = f.read()
        try:
            feed_games = simplejson.loads(feed_contents)['games']
        except ValueError:
            feed_games = None
    except urllib2.HTTPError:
        feed_games = None
        raise
    return feed_games    
    
def process_feed(feed_type, feed_games):
    updated = 0
    added = 0
    adapter = adapters.REGISTERED_ADAPTERS[feed_type]()
    for feed_game in feed_games:
        game_dct = adapter.preprocess(feed_game)
        game_dirty = False
        try:
            game = Game.objects.get(slug=game_dct['slug'])
            if not game.updated == game_dct['updated']:
                for k,v in game_dct.items():
                    setattr(game, k, v)
                game.save()
                # flag game for post processing
                game_dirty = True
                updated += 1
        except Game.DoesNotExist:
            game = Game.objects.create(**game_dct)
            # flag game for post processing
            game_dirty = True
            added += 1
        if game_dirty:
            adapter.postprocess(game)
    return (updated, added)
            
            
def feed_run():
    feeds = Feed.objects.all()
    print "=" * 80
    print "Downloading and processing game feeds. This may take a while."
    for feed in feeds:
        print "Processing %s feed..." % feed.feed_name
        games = load_feed(feed)
        updated, added = process_feed(feed.feed_type, games)
        print "%s processing finished. %d updated. %d added." % (feed.feed_name, updated, added)
        print "=" * 80
        
def process_download_queue():
    pass        
     
def import_all():
    feed_run()
            
if __name__ == '__main__':
    import_all()